package pkg

import (
	"2302a/audio_podcast/api/resp"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"net/http"
	"time"
)

type MyCustomClaims struct {
	UserId uint `json:"user_id"`
	jwt.RegisteredClaims
}

func CreateJwtToken(userId uint, duration time.Duration, jwtKey string) string {
	claims := MyCustomClaims{
		userId,
		jwt.RegisteredClaims{
			// A usual scenario is to set the expiration time relative to the current time
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(duration)),
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	ss, err := token.SignedString([]byte(jwtKey))
	fmt.Println(ss, err)
	if err != nil {
		print(err)
		return ""
	}
	return ss
}

func AuthJwt(jwtKey string) gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenStr := c.Request.Header.Get("x-token")
		if tokenStr == "" {
			resp.Error(c, http.StatusUnauthorized, "未登录", nil)
			c.Abort()
			return
		}
		token, err := jwt.ParseWithClaims(tokenStr, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
			return []byte(jwtKey), nil
		})
		if err != nil {
			resp.Error(c, http.StatusUnauthorized, "非法token", nil)
			c.Abort()
			return
		}
		claims, _ := token.Claims.(*MyCustomClaims)
		if claims.UserId == 0 {
			resp.Error(c, http.StatusUnauthorized, "解析token", nil)
			c.Abort()
			return
		}
		c.Set("userId", claims.UserId)
	}
}
